package com.snowflake.ecatalog.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springside.modules.utils.DateProvider;

import com.snowflake.ecatalog.contant.ResourceInfoType;
import com.snowflake.ecatalog.entity.ResourceInfo;

/**
 * 
 * 文件上传下载工具类
 */
public class FileOperateUtil {
	private static final String UPLOADDIR = "uploadDir";

	/**
	 * 删除文件
	 * 
	 * @param resourceInfoList
	 * @return
	 * @throws Exception
	 */
	public static void delete(List<ResourceInfo> resourceInfoList) {
		File deleteFile = null;
		for (ResourceInfo resourceInfo : resourceInfoList) {
			deleteFile = new File(resourceInfo.getPhysicalPath() + resourceInfo.getFileName());
			FileSystemUtils.deleteRecursively(deleteFile);
		}
	}

	/**
	 * 将上传的文件进行重命名
	 * 
	 * @param name
	 * @return
	 */
	private static String rename(HttpServletRequest request) {

		String uploadFileName = request.getParameter("uploadFileName");
		if (StringUtils.isBlank(uploadFileName)) {
			StringBuffer newFileName = new StringBuffer(String.valueOf(DateProvider.DEFAULT.getDate().getTime()));
			if (newFileName.length() > 13) {
				newFileName.setLength(13);
			}
			uploadFileName = newFileName.toString();
		}

		return uploadFileName;
	}

	/**
	 * 设置文件扩展名
	 * 
	 * @param name
	 * @return
	 */
	private static String setFileExtension(String storeName, MultipartFile mFile) {
		StringBuffer newFileName = new StringBuffer(storeName);
		String originalFilename = mFile.getOriginalFilename();
		// 设置类型别名
		newFileName.append(ResourceInfoType.alias(Integer.valueOf(mFile.getName())));
		if (originalFilename.indexOf(".") != -1) {
			newFileName.append(originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase());
		}

		return newFileName.toString();
	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param profileNumber
	 * @return
	 * @throws Exception
	 */
	public static List<ResourceInfo> upload(HttpServletRequest request, String profileNumber) throws Exception {

		List<ResourceInfo> result = new ArrayList<ResourceInfo>();

		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = mRequest.getFileMap();

		// 加上彩页profile的别名
		String physicalPath = request.getSession().getServletContext().getRealPath("/");
		// 如果不是File.separator结尾的，就加上File.separator。解决jetty和tomcat环境下，获取的RealPath路径不同问题
		if (!physicalPath.endsWith(File.separator)) {
			physicalPath = physicalPath + File.separator;
		}
		physicalPath = physicalPath + UPLOADDIR + File.separator + profileNumber + File.separator;

		// 外网文件访问路径
		String webPath = request.getContextPath() + "/" + UPLOADDIR + "/" + profileNumber + "/";

		String storeName = rename(request);
		ResourceInfo resourceInfo = null;
		MultipartFile mFile = null;
		File targetFile = null;
		String fileName = null;
		for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {

			Map.Entry<String, MultipartFile> entry = it.next();
			mFile = entry.getValue();

			String resouceInfoId = request.getParameter(mFile.getName());
			// resourceId已存在
			if (StringUtils.isNotBlank(resouceInfoId) && NumberUtils.isNumber(resouceInfoId)) {
				resourceInfo = new ResourceInfo(Long.valueOf(resouceInfoId));
				result.add(resourceInfo);
			} else if (mFile.getSize() > 0) {
				// 如果上传的文件大小大于0：就是有上传文件
				// 设置文件扩展名
				fileName = setFileExtension(storeName, mFile);

				targetFile = new File(physicalPath, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				mFile.transferTo(targetFile);

				resourceInfo = new ResourceInfo();
				resourceInfo.setPhysicalPath(physicalPath);
				resourceInfo.setWebPath(webPath);
				resourceInfo.setFileName(fileName);
				resourceInfo.setSequence(Integer.valueOf(mFile.getName()));

				result.add(resourceInfo);
			}
		}
		return result;
	}

	/**
	 * 下载
	 * 
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String storeName,
			String contentType, String realName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
		String downLoadPath = ctxPath + storeName;

		long fileLength = new File(downLoadPath).length();

		response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}

	/**
	 * 获取resourceInfo的fileName名称
	 * 
	 * @param resourceInfos
	 */
	public static String getFileNameByResourceInfos(List<ResourceInfo> resourceInfos) {
		String fileName = null;
		if (CollectionUtils.isNotEmpty(resourceInfos)) {
			ResourceInfo resourceInfo = resourceInfos.get(0);
			fileName = getFileNameByResourceInfos(resourceInfo);
		}
		return fileName;
	}

	/**
	 * 获取resourceInfo的fileName名称
	 * 
	 * @param resourceInfo
	 */
	public static String getFileNameByResourceInfos(ResourceInfo resourceInfo) {
		String fileName = null;
		if (resourceInfo != null) {
			fileName = resourceInfo.getFileName();
			if (StringUtils.isNotBlank(fileName)) {
				if (fileName.indexOf("_") != -1) {
					fileName = fileName.substring(0, fileName.lastIndexOf("_"));
				} else if (fileName.indexOf(".") != -1) {
					fileName = fileName.substring(0, fileName.lastIndexOf("."));
				}
			}
		}
		return fileName;
	}
}
